package com.str.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangWu
 * * @date 2022/3/16 16:07
 * @description Redis工具类
 */
@Component
@Slf4j
public class RedisUtil {
    private static String CONTEXT="str_";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(CONTEXT+key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error("RedisUtil expire Exception",e);
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        try {
            return redisTemplate.getExpire(CONTEXT+key, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("RedisUtil getExpire Exception",e);
            return 0L;
        }
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(CONTEXT+key);
        } catch (Exception e) {
            log.error("RedisUtil hasKey Exception",e);
            return false;
        }
    }

    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    public void del(String... key) {
        try {
            for (int i = 0; i < key.length; i++) {
                redisTemplate.delete(CONTEXT+key[i]);
            }
        } catch (Exception e) {
            log.error("RedisUtil del Exception",e);
        }
    }

    /**
     * 递增
     * @param key 键
     * @return
     */
    public long incr(String key) {
        return redisTemplate.opsForValue().increment(CONTEXT+key);
    }


    // ============================String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public <T> T get(String key,Class<T> clazz) {
        try {
            Object value = redisTemplate.opsForValue().get(CONTEXT+key);
            if(value == null || "".equals(value.toString())){
                return null;
            }
            if(clazz.equals(String.class)){
                return (T)value;
            }
            if(clazz.equals(Integer.class)){
                Integer temp = Integer.parseInt(value.toString());
                return (T)temp;
            }
            if(clazz.equals(Float.class)){
                Float temp = Float.parseFloat(value.toString());
                return (T)temp;
            }
            if(clazz.equals(Double.class)){
                Double temp = Double.parseDouble(value.toString());
                return (T)temp;
            }
            if(clazz.equals(Short.class)){
                Short temp = Short.parseShort(value.toString());
                return (T)temp;
            }
            if(clazz.equals(Long.class)){
                Long temp = Long.parseLong(value.toString());
                return (T)temp;
            }
            if(clazz.equals(Boolean.class)){
                Boolean temp = Boolean.parseBoolean(value.toString());
                return (T)temp;
            }
            return toJavaObject(value.toString(),clazz);
        } catch (Exception e) {
            log.error("RedisUtil get Exception",e);
        }
        return null;
    }

    /**
     * 普通缓存放入并设置时间
     * @param key 键
     * @param value 值
     * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key, Object value, long time) {
        try {
            String temp = "";
            if(value instanceof String || value instanceof Integer || value instanceof Float
                    || value instanceof Short || value instanceof Long || value instanceof Double
                    || value instanceof Boolean){
                temp = value.toString();
            }else{
                temp = JSONObject.toJSONString(value);
            }
            if (time > 0) {
                redisTemplate.opsForValue().set(CONTEXT+key, temp, time, TimeUnit.SECONDS);
            } else {
                redisTemplate.opsForValue().set(CONTEXT+key, temp);
            }
            return true;
        } catch (Exception e) {
            log.error("RedisUtil set Exception",e);
            return false;
        }
    }

    /**
     * 缓存一个List<T>集合
     * @param key key
     * @param list 值
     * @param clazz 数据类型
     * @param expire 有效期 单位秒
     * @return 成功返回1,失败返回0
     */
    public <T> int setList(String key, List<T> list,Class<T> clazz, int expire) {
        int res = 0;
        try {
            redisTemplate.delete(CONTEXT + key);
            for(T t : list){
                Long result = null;
                if(clazz.equals(String.class) || clazz.equals(Integer.class) || clazz.equals(Float.class) || clazz.equals(Double.class) || clazz.equals(Short.class) || clazz.equals(Long.class) || clazz.equals(Boolean.class)){
                    result = redisTemplate.opsForList().rightPush(CONTEXT+key,t);
                }else {
                    String value = JSONObject.toJSONString(t);
                    result = redisTemplate.opsForList().rightPush(CONTEXT + key, value);
                }
                if (result != null && result != 0) {
                    res++;
                }
            }
            if(expire > 0){
                redisTemplate.expire(CONTEXT + key, expire,TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            log.error("RedisUtil setList Exception",e);
        }
        return res;
    }

    /**
     * 获取List<T>集合
     * @param key key
     * @param clazz 返回数据类型
     * @return 返回结果
     */
    public <T> List<T> getList(String key, Class<T> clazz) {
        List<T> resList = new ArrayList<T>();
        try {
            List<Object> range = redisTemplate.opsForList().range(CONTEXT+key,0,-1);
            if(range == null || range.isEmpty()){
                return null;
            }
            for(Object obj : range){
                if(clazz.equals(String.class) || clazz.equals(Integer.class) || clazz.equals(Float.class) || clazz.equals(Double.class) || clazz.equals(Short.class) || clazz.equals(Long.class) || clazz.equals(Boolean.class)){
                    resList.add((T) obj);
                }else{
                    Object object = toJavaObject(obj.toString(),clazz);
                    resList.add((T) object);
                }
            }
            return resList;
        }catch (Exception e){
            log.error("RedisUtil getList Exception",e);
        }
        return null;
    }

    private <T> T toJavaObject(String value,Class<T> clazz){
        JSONObject jsonObject = JSON.parseObject(value);
        return JSONObject.toJavaObject(jsonObject,clazz);
    }
}